package com.xyhuo.leetcode;

public class MinSubArrayLen {

    public int minSubArrayLen(int target, int[] nums) {
        int left = 0, right = 0;
        int sum = 0;
        int result = 100001;

        while (left <= right) {
            if (sum < target) {
                if (right >= nums.length) {
                    break;
                }
                sum += nums[right];
                right++;
            } else if (sum >= target) {
                sum -= nums[left];
                int len = right - left;
                if (len < result) {
                    result = len;
                }
                left++;
            }
        }
        if (right == nums.length && sum > target) {
            int tmp = 0;
            for (int i = right - 1; i >= left; i--) {
                tmp += nums[i];
                if (tmp >= target) {
                    int len = nums.length - i;
                    if (len < result) {
                        result = len;
                    }
                    break;
                }
            }
        }
        if (result == 100001) {
            return 0;
        }

        return result;
    }

    public static void main(String[] args) {
        MinSubArrayLen m = new MinSubArrayLen();
//        int[] nums = {2, 3, 1, 2, 4, 3};
        int[] nums1 = {1, 2, 3, 4, 5};
//        m.minSubArrayLen(7, nums);

        m.minSubArrayLen(15, nums1);
    }
}
